<template>
  <div class="sales-analysis-page">
    <!-- 销售漏斗 -->
    <el-card class="chart-card">
      <template #header>销售转化漏斗</template>
      <div ref="funnelChartRef" class="chart"></div>
    </el-card>

    <!-- 品牌分析 -->
    <el-card class="chart-card">
      <template #header>品牌销售分析</template>
      <div ref="brandAnalysisChartRef" class="chart"></div>
    </el-card>

    <!-- 商品分析 -->
    <el-card class="chart-card">
      <template #header>商品销售排行</template>
      <div class="product-table">
        <el-table :data="topProducts" stripe>
          <el-table-column prop="rank" label="排名" width="80" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.rank <= 3" :type="getRankType(row.rank)" size="small">
                {{ row.rank }}
              </el-tag>
              <span v-else>{{ row.rank }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" min-width="200" />
          <el-table-column prop="brand" label="品牌" width="120" />
          <el-table-column prop="price" label="价格" width="100">
            <template #default="{ row }">
              ¥{{ formatNumber(row.price) }}
            </template>
          </el-table-column>
          <el-table-column prop="salesVolume" label="销量" width="100" align="center" />
          <el-table-column prop="revenue" label="收入" width="120">
            <template #default="{ row }">
              ¥{{ formatNumber(row.revenue) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 价格区间分析 -->
    <el-card class="chart-card">
      <template #header>价格区间分布</template>
      <div ref="priceRangeChartRef" class="chart"></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts/core'
import { FunnelChart, BarChart, PieChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { onMounted, ref, reactive } from 'vue'
import { reportService, type BrandPerformanceData, type SalesFunnelData, type TopProductsData, type PriceRangeData } from '@/api/reportService'

echarts.use([
  FunnelChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer
])

const funnelChartRef = ref<HTMLDivElement | null>(null)
const brandAnalysisChartRef = ref<HTMLDivElement | null>(null)
const priceRangeChartRef = ref<HTMLDivElement | null>(null)

const brandData = reactive<BrandPerformanceData>({
  brandNames: [],
  productCounts: [],
  totalSales: [],
  totalRevenue: []
})

const topProducts = ref<TopProductsData['topProducts']>([])
const salesFunnelData = ref<SalesFunnelData['funnelData']>([])
const priceRangeData = ref<PriceRangeData>({ ranges: [], counts: [] })

const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const getRankType = (rank: number) => {
  switch (rank) {
    case 1: return 'danger'
    case 2: return 'warning'
    case 3: return 'success'
    default: return 'info'
  }
}

const loadBrandData = async () => {
  try {
    const data = await reportService.getBrandPerformance()
    Object.assign(brandData, data)
    initBrandAnalysisChart()
  } catch (error) {
    console.error('加载品牌数据失败:', error)
  }
}

const loadSalesFunnelData = async () => {
  try {
    const data = await reportService.getSalesFunnel()
    salesFunnelData.value = data.funnelData
    initFunnelChart()
  } catch (error) {
    console.error('加载销售漏斗数据失败:', error)
  }
}

const loadTopProductsData = async () => {
  try {
    const data = await reportService.getTopProducts()
    topProducts.value = data.topProducts
  } catch (error) {
    console.error('加载商品排行榜数据失败:', error)
  }
}

const loadPriceRangeData = async () => {
  try {
    const data = await reportService.getPriceRangeDistribution()
    priceRangeData.value = data
    initPriceRangeChart()
  } catch (error) {
    console.error('加载价格区间分布数据失败:', error)
  }
}

const initFunnelChart = () => {
  if (!funnelChartRef.value) return
  
  const chart = echarts.init(funnelChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        type: 'funnel',
        left: '10%',
        top: 20,
        bottom: 20,
        width: '80%',
        min: 0,
        max: 100,
        label: { show: true, formatter: '{b}: {c}%' },
        data: salesFunnelData.value.map(item => ({
          value: item.value,
          name: item.name
        }))
      }
    ]
  })
}

const initBrandAnalysisChart = () => {
  if (!brandAnalysisChartRef.value) return
  
  const chart = echarts.init(brandAnalysisChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'axis' },
    legend: { bottom: 0 },
    grid: { left: 30, right: 20, top: 20, bottom: 50 },
    xAxis: { 
      type: 'category', 
      data: brandData.brandNames,
      axisLabel: { rotate: 45 }
    },
    yAxis: [
      { type: 'value', name: '销量' },
      { type: 'value', name: '收入(¥)' }
    ],
    series: [
      {
        name: '销量',
        type: 'bar',
        yAxisIndex: 0,
        data: brandData.totalSales,
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '收入',
        type: 'line',
        yAxisIndex: 1,
        data: brandData.totalRevenue.map(rev => rev / 1000), // 转换为千元单位
        itemStyle: { color: '#67C23A' }
      }
    ]
  })
}

const initPriceRangeChart = () => {
  if (!priceRangeChartRef.value) return
  
  const chart = echarts.init(priceRangeChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        name: '价格区间',
        type: 'pie',
        radius: '60%',
        data: priceRangeData.value.ranges.map((range, index) => ({
          name: range,
          value: priceRangeData.value.counts[index]
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

onMounted(async () => {
  await Promise.all([
    loadBrandData(),
    loadSalesFunnelData(),
    loadTopProductsData(),
    loadPriceRangeData()
  ])
})
</script>

<style scoped>
.sales-analysis-page {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
}

.chart-card {
  min-height: 400px;
}

.chart {
  width: 100%;
  height: 350px;
}

.product-table {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .sales-analysis-page {
    grid-template-columns: 1fr;
  }
}
</style>
